// reducer action
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getStudentsAPI, deleteStudentByIdAPI, updateStudentByIdAPI, addStudentByIdAPI } from "../api/student";

// 获取所有学生 的异步通信
export const getStusAsync = createAsyncThunk(
    'stu/getStudents',
    async(stuId, thunkAPI) => {
        const { data } = await getStudentsAPI()
        thunkAPI.dispatch(initialStore(data))
    },
)

export const deleteStuAsync = createAsyncThunk(
    'stu/deleteStudent',
    async(stuId, thunkAPI) => {
        await deleteStudentByIdAPI(stuId)
        thunkAPI.dispatch(getStusAsync())
    }
)

export const addStudent = createAsyncThunk(
    "stu/addStudent",
    async(data, thunkAPI) => {
        await addStudentByIdAPI(data)
        thunkAPI.dispatch(getStusAsync())
    }
)

export const updateStudent = createAsyncThunk(
    "stu/updateStudent",
    async(payload, thunkAPI) => {
        await updateStudentByIdAPI(payload.stuId, payload.stu)
        thunkAPI.dispatch(getStusAsync())
    }
)

const stuSlice = createSlice({
    name: "studentSlice",
    initialState: {
        stuList: [],
    },
    reducers: {
        // 初始化仓库
        initialStore: (state, { payload }) => {
            state.stuList = payload
        },
    },
})

export const { initialStore } = stuSlice.actions
export default stuSlice.reducer